package org.study.clickhouse.plus.boot.controller;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.study.clickhouse.plus.boot.model.User;
import org.study.clickhouse.plus.boot.service.UserService;
import org.study.clickhouse.plus.boot.util.ClickHouseUtils;

import java.sql.*;
import java.util.List;

/**
 * 类的描述
 *
 * @author Administrator
 * @date 2022-03-18
 */
@Slf4j
@RestController
@RequestMapping("/ch")
public class ClickHouseController {
    @Resource
    private UserService userService;

    @RequestMapping("/db")
    public List<String> showDatabases() {
        List<String> result = Lists.newArrayList();
        String sql = "show databases";
        try (Connection connection = ClickHouseUtils.getConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                String dbName = rs.getString(1);
                result.add(dbName);
            }
        } catch (SQLException ex) {
            log.error("查看所有数据库异常", ex);
        }
        return result;
    }

    @RequestMapping("/table")
    public List<String> showTables() {
        List<String> result = Lists.newArrayList();
        String sql = "show tables";
        try (Connection connection = ClickHouseUtils.getConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                String tableName = rs.getString(1);
                result.add(tableName);
            }
        } catch (SQLException ex) {
            log.error("查看所有表异常", ex);
        }
        return result;
    }

    @RequestMapping("/id/{id}")
    public User findById(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        log.info("查询 ID={}，的学生信息，结果：{}", id, JSON.toJSONString(user));
        return user;
    }

    @RequestMapping("/page/{pageSize}/{pageNum}")
    public PageInfo<User> findByPage(@PathVariable("pageSize") Integer pageSize, @PathVariable("pageNum") Integer pageNum) {
        PageInfo<User> userPageInfo = userService.offsetPage1(pageSize, pageNum);
        log.info("分页信息：{}", JSON.toJSONString(userPageInfo));
        log.info("学生信息：{}", JSON.toJSONString(userPageInfo.getList()));
        return userPageInfo;
    }
}
